#!/bin/sh /etc/rc.common

START=99
LOGGER="logger -t [iPerf3-Server]"

start() {
	local basic_list="main_enable"
	local server_list="port delay extra_options enable_server"
	for i in $(echo $basic_list)
	do
		local eval $i="$(uci_get_by_type iperf3-server 0 $i)"
	done ; unset i
	if [ "$main_enable" == 1 ]
	then
		server_number=$(uci show iperf3-server 2> /dev/null | egrep '@servers\[[0-9]\]+=servers' | wc -l)
		# server_number=$(uci show iperf3-server 2> /dev/null | egrep -o '@servers\[[0-9]\]+=servers' | awk 'END {print}' | egrep -o "[0-9]")
		for u in $(seq 0 $((${server_number} - 1)))
		do
			for i in $server_list
			do
				eval ${i}=$(uci_get_by_type servers $u $i)
			done ; unset i
			if [ "$enable_server" == 1 ]
			then
				sleep $delay
				$LOGGER "Starting iPerf3 Server [$u] with Port [$port] ..."
				old_process="$(ps -efww | grep 'iperf3 -s -D -p $port' | grep -v 'grep' | awk '{print $1}')"
				[ "$old_process" ] && kill -9 "$old_process" 2> /dev/null
				$(command -v iperf3) -s -D -p $port $extra_options
				#procd_open_instance
				#procd_set_param command sleep $delay ; $(command -v iperf3) -s -D -p $port $extra_options
				#procd_set_param respawn 3000 3 10
				#procd_close_instance
			fi
			unset enable_server delay
		done ; unset u
	else
		$LOGGER "iPerf3 Server is disabled ..."
		stop_service
	fi
}

stop() {
	$LOGGER "Stopping iPerf3 Server ..."
	ps -efww | grep 'iperf3 -s -D' | grep -v 'grep' | awk '{print $1}' | xargs kill -9
}

service_triggers() {
	procd_add_reload_trigger "iperf3-server"
}

uci_get_by_type() {
	local ret=$(uci get iperf3-server.@$1[$2].$3 2>/dev/null)
	echo ${ret:=$4}
}
